//
//  AddressInputViewController.m
//  PigMarket
//
//  Created by mac on 2019/3/25.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AddressInputViewController.h"
#import "AddressInputCell.h"
#import "STPickerArea.h"
#import <ContactsUI/ContactsUI.h>
#import "TribeRangeViewController.h"

@interface AddressInputViewController ()<UITableViewDataSource,UITableViewDelegate>
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;

/**
 dataArr
 */
@property (nonatomic , strong) NSArray *dataArr;
/**
 requestDataArr
 */
@property (nonatomic , strong) NSMutableArray *requestDataArr;
/**
 地图传值Dic
 */
@property (nonatomic , strong) NSDictionary *mapDic;
@end

@implementation AddressInputViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.baseNavView.navTitleLabel.text = self.title;
    [self setUpView];
}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.baseNavView.bottom);
    }];
}

- (void) initAction {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectCellLocation:) name:NotificationDidSelectCellLocationChange object:nil];

}

- (void)initData {
    
    if ([self.title isEqualToString:ModifyAddressTitle]) {
        NSString *name = self.addressModel.userName;
        NSString *phone = self.addressModel.phone;
        NSString *area = self.addressModel.localName;
        NSString *distance = self.addressModel.details;
        NSString *tag = [NSString stringWithFormat:@"%@",self.addressModel.tags];
        NSString *defaultStatus = [NSString stringWithFormat:@"%@",self.addressModel.isDefault];

        self.dataArr = @[@[@{@"title":@"收货人",@"detail":name,@"placeholder":@"",@"right":@"addressbook"},
                           @{@"title":@"手机号",@"detail":phone,@"placeholder":@"",@"right":@""},
                           @{@"title":@"所在区域",@"detail":area,@"placeholder":@"",@"right":@"arrows"},
                           @{@"title":@"详细地址",@"detail":distance,@"placeholder":@"",@"right":@""}],
                         @[@{@"title":@"标签",@"detail":tag,@"placeholder":@"",@"right":@"addresstype"}],
                         @[@{@"title":@"设为默认地址",@"detail":defaultStatus,@"placeholder":@"",@"right":@"switch"}]];
     
    }else if ([self.title isEqualToString:AddAddressTitle]){
        self.dataArr = @[@[@{@"title":@"收货人",@"detail":@"",@"placeholder":@"请填写收货人姓名",@"right":@"addressbook"},
                           @{@"title":@"手机号",@"detail":@"",@"placeholder":@"请填写收货人手机号",@"right":@""},
                           @{@"title":@"所在区域",@"detail":@"",@"placeholder":@"省市区、乡镇等",@"right":@"arrows"},
                           @{@"title":@"详细地址",@"detail":@"",@"placeholder":@"街道、楼牌号",@"right":@""}],
                         @[@{@"title":@"标签",@"detail":@"",@"placeholder":@"",@"right":@"addresstype"}],
                         @[@{@"title":@"设为默认地址",@"detail":@"",@"placeholder":@"",@"right":@"switch"}]];
    }
    
}
#pragma mark - delegate
//tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArr[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 110;
    }else {
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110)];
    
    UIButton *addAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addAddressBtn.frame = CGRectMake(30, 60, SCREEN_WIDTH-60, 48);

    [addAddressBtn setTitle:@"保存" forState:UIControlStateNormal];
    [addAddressBtn setBackgroundImage:[UIImage imageNamed:@"btn_nomal_bg"] forState:UIControlStateNormal];
    [addAddressBtn addTarget:self action:@selector(saveAddressTapped) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:addAddressBtn];
   
    return footerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressInputCell *cell = [AddressInputCell cellWithTableView:tableView];
    if (self.dataArr.count > indexPath.section) {
        if ([self.dataArr[indexPath.section] count] > indexPath.row) {
            [cell configCellWithInfoDic:self.dataArr[indexPath.section][indexPath.row] indexPath:indexPath];
        }
    }

    //通讯录block
    [cell setAddressBookBlock:^{
//        [self getAddressBook];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0://收货人
                
                break;
            case 1://手机号
                
                break;
            case 2://所在地区
            {
                [self.navigationController pushViewController:[[TribeRangeViewController alloc] init] animated:YES];

            }
                break;
            case 3://详细地址
                break;
            default:
                break;
        }
    }else if (indexPath.section == 1) {
        
    }else {
        
    }
}


//通讯录delegate
/*设置权限
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    CNPhoneNumber *num = nil;
    NSString *string = nil;
    if (contact.phoneNumbers.count > 0) {
        num = contact.phoneNumbers[0].value;
        string = [NSString stringWithFormat:@"%@%@%@",contact.familyName,contact.givenName,[num valueForKey:@"digits"]];
    }else {
        string = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
    }
    PMLog(@"通讯录：%@",string);
}
 */
#pragma mark - target action
//接收地图选择的数据
- (void)didSelectCellLocation:(NSNotification *)notification {
    self.mapDic = notification.userInfo;
    AddressInputCell *cell = (AddressInputCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    cell.detailField.text = [self.mapDic objectForKey:@"localName"];
}
//保存
- (void)saveAddressTapped {
    NSString *lon = [self.mapDic objectForKey:@"lat"];
    NSString *lat = [self.mapDic objectForKey:@"lon"];
    NSString *localCode = [self.mapDic objectForKey:@"localCode"];
    //省市区
    NSString *localName = [self.mapDic objectForKey:@"localName"];

    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    NSString *name = [self getInputAddressInfoWithSection:0 row:0];
    NSString *phone = [self getInputAddressInfoWithSection:0 row:1];
    NSString *subdistrict = [self getInputAddressInfoWithSection:0 row:3];//街道地址
    NSString *addressTag = [self getAddressTag];
    NSNumber *defaultAddress = [self getDefaultStatus];
    if ([name isBlankString]) {
        [self toastWithContent:@"请输入收货人"];
        return;
    }
    if ([phone isBlankString]) {
        [self toastWithContent:@"请输入手机号"];
        return;
    }
    if ([localName isBlankString] || [subdistrict isBlankString]) {
        [self toastWithContent:@"请输入地址"];
        return;
    }
    if ([self.title isEqualToString:AddAddressTitle]) {
        AddressParam *param = [[AddressParam alloc] init];
        //经纬度
        param.lon = lon;
        param.lat = lat;
        param.localName = localName;
        param.details = subdistrict;
        param.localCode = localCode;
        param.userName = name;
        param.phone = phone;
        param.isDefault = defaultAddress;
        param.memberId = memberId;
        param.tags = addressTag;
        [[[PigMarketApi sharedInstance] addAddressWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }else if ([self.title isEqualToString:ModifyAddressTitle]) {
        AddressParam *param = [[AddressParam alloc] init];
        //经纬度
        param.lon = lon;
        param.lat = lat;
        param.receiveAddressId = self.addressModel.receiveAddressId;
        param.localName = localName;
        param.details = subdistrict;
        param.localCode = localCode;
        param.userName = name;
        param.phone = phone;
        param.isDefault = defaultAddress;
        param.memberId = memberId;
        param.tags = addressTag;
        [[[PigMarketApi sharedInstance] editAddressWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
}
#pragma mark - private method
- (NSString *)getInputAddressInfoWithSection:(NSInteger)section row:(NSInteger)row {
    AddressInputCell *cell = (AddressInputCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
    return cell.detailField.text;
}
- (NSString *)getAddressTag{
  AddressInputCell *cell = (AddressInputCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    if (cell.homeBtn.selected) {
        return cell.homeBtn.titleLabel.text;
    }else if (cell.schoolBtn.selected) {
        return cell.schoolBtn.titleLabel.text;
    }else if (cell.companyBtn.selected) {
        return cell.schoolBtn.titleLabel.text;
    }else {
        return nil;
    }
}
- (NSNumber *)getDefaultStatus {
    AddressInputCell *cell = (AddressInputCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    if (cell.defaultAddressSwitch.on) {
        return @1;
    }else {
        return @0;
    }
}
//通讯录delegate
/*设置权限
 - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
 CNPhoneNumber *num = nil;
 NSString *string = nil;
 if (contact.phoneNumbers.count > 0) {
 num = contact.phoneNumbers[0].value;
 string = [NSString stringWithFormat:@"%@%@%@",contact.familyName,contact.givenName,[num valueForKey:@"digits"]];
 }else {
 string = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
 }
 PMLog(@"通讯录：%@",string);
 }
 */
//获取通讯录
- (void)getAddressBook {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                //未授权
                [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您未开启通讯录权限，请前往设置中心开启" confirmBtnTitle:@"确定" confirmBlock:^{
                    
                }  cancelBlock:nil];
            }else {
                //已授权
                CNContactPickerViewController *picker = [CNContactPickerViewController new];
                picker.delegate = self;
                //只显示手机号码
                picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
                [self presentViewController:picker animated:YES completion:nil];
            }
        }];
    }
    
    if (status == CNAuthorizationStatusAuthorized) {
        CNContactPickerViewController *picker = [CNContactPickerViewController new];
        picker.delegate = self;
        //只显示手机号码
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController:picker animated:YES completion:nil];

    }else {
        [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您未开启通讯录权限，请前往设置中心开启" confirmBtnTitle:@"确定" confirmBlock:^{
            
        } cancelBlock:nil];
    }
}
#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}
- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSArray alloc] init];
    }
    return _dataArr;
}
- (NSMutableArray *)requestDataArr {
    if (!_requestDataArr) {
        _requestDataArr = [[NSMutableArray alloc] init];
    }
    return _requestDataArr;
}
@end
